package org.standard.commons.tlds;

import java.util.Locale;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.standard.commons.utils.Utils;


public class TagOptionValue extends TagSupport {
	
	private static final long serialVersionUID = -3166812535628021005L;

	private String optionName = null;//
	private String value = null;//
	private boolean skipTop;

	@Override
	public int doEndTag() throws JspException {

		return EVAL_PAGE;
	}

	@Override
	public int doStartTag() throws JspException {
		
		try{
			
			//Locale locale = pageContext.getRequest().getLocale(); 得到的是浏览器的语言
			HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
			Locale locale = (Locale) request.getSession().getAttribute("locale");
			Properties props = PropertiesFileConstants.getPropertiesFileConstants(locale);
			
			String propsValue = props.get(optionName).toString(); 
			String propsValueArray [] = propsValue.split(",");
			
			String outString = "";
			
			if (skipTop) {
				String nameValueArrayFirst [] = propsValueArray[0].split(":");
				if (!Utils.isStringNull(value) && nameValueArrayFirst[1].trim().equals(value)) {
					outString = "";
				} else {
					for (int i = 0; i < propsValueArray.length; i++){
						String nameValueArray [] = propsValueArray[i].split(":");
						if(!Utils.isStringNull(value) && nameValueArray[1].trim().equals(value)){
							outString = nameValueArray[0].trim();
							break;
						}
					}
				}
			} else {
				for (int i = 0; i < propsValueArray.length; i++){
					String nameValueArray [] = propsValueArray[i].split(":");
					if(!Utils.isStringNull(value) && nameValueArray[1].trim().equals(value)){
						outString = nameValueArray[0].trim();
						break;
					}
				}
			}
			JspWriter out = pageContext.getOut();
	        out.print(outString);
	    } catch (Exception e){
	        e.printStackTrace();
	    }
	    return EVAL_BODY_INCLUDE;

	}

	public void setOptionName(String optionName) {
		this.optionName = optionName;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public void setSkipTop(boolean skipTop) {
		this.skipTop = skipTop;
	}

	

}
